package com.dongdongshop.shiro;


import com.dongdongshop.exception.LoginException;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerLoginService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

//继承抽象类 实现抽象方法
public class LoginRealm extends AuthorizingRealm {

    @DubboReference
    private SellerLoginService sellerLoginService;

    @Override//授权方法
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权");
        //当访问呢到需要授权的页面时 在此进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<String> perms = new ArrayList<>();
        perms.add("crud_delete");
        perms.add("crud_update");
        info.addStringPermissions(perms);
        return info;
    }

    @Override//认证方法(登录方法)
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入登录");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String name = token.getUsername();
        TbSeller tbSeller = sellerLoginService.selectBy(name);
        if (tbSeller == null) {
            return null;
        }
        if(tbSeller.getStatus().equals("0")){
            throw new LoginException("审核异常");
        }
       //1.表示登录成功后的对象 2.数据库中的密码 3盐 4.用户的真实名字    ****校验密码
        return new SimpleAuthenticationInfo(tbSeller,tbSeller.getPassword(),ByteSource.Util.bytes(tbSeller.getSalt()), tbSeller.getSellerId());
    }
}
